package com.spzx.payment.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rabbitmq.client.Channel;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.PaymentInfoService;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class SpzxPaymentMqListener {
    @Resource
    PaymentInfoService paymentInfoService;
    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value = "spzx.order.exchange",type = ExchangeTypes.TOPIC),
                    value = @Queue(value = "spzx.order.payment.close.queue"),
                    key = {"spzx.order.close.success"}
            )
    })
    public void paymentNotify(String orderNo , Message msg , Channel channel){
        try {
            //业务：更新支付日志
            paymentInfoService.update(Wrappers.lambdaUpdate(PaymentInfo.class)
                    .eq(PaymentInfo::getOrderNo , orderNo)
                    .eq(PaymentInfo::getPaymentStatus , 0 )
                    .set(PaymentInfo::getPaymentStatus , -1));
            channel.basicAck(msg.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
            try {
                if(msg.getMessageProperties().isRedelivered()){
                    channel.basicReject(msg.getMessageProperties().getDeliveryTag() ,false);
                }else{
                    channel.basicNack(msg.getMessageProperties().getDeliveryTag() ,false,true);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

    }

}
